const moment = require('moment')
const { mysqlPool } = require('../config/db')

class Message {
    // （取消）关注好友时，添加一条消息
    // userId: 当前用户id，followId: 关注的好友id
    static async handleFollow(msgType, userId, followId) {
        // 查询用户信息和好友信息
        const [userInfo, followInfo] = await Promise.all([
            mysqlPool.execute('select * from users where id = ?', [userId]),
            mysqlPool.execute('select * from users where id = ?', [followId])
        ])

        const content = `${userInfo[0][0].nickName ? userInfo[0][0].nickName : userInfo[0][0].username} ${msgType === 'follow' ? '关注' : '取关'}了你`
        const createTime = moment().format('YYYY-MM-DD HH:mm:ss')
        const sql = `insert into message_center (sender_id, recipient_id, type, is_read, content, create_time) values (?, ?, ?, ?, ?, ?)`
        const [result] = await mysqlPool.execute(sql, [
            userId,
            followId,
            msgType === 'follow' ? 1 : 2,
            0,
            content,
            createTime
        ])

        // 添加成功
        if (result.affectedRows > 0) {
            return { id: result.insertId, content, type: msgType === 'follow' ? 1 : 2, createTime, isRead: 0 }
        }

        return false
    }

    // 获取消息列表
    static async getMsgList(userId, currentPage, pageSize) {
        const totalSql = `select count(*) as total from message_center where recipient_id = ?`
        const [totalResult] = await mysqlPool.execute(totalSql, [userId])
        const total = totalResult[0].total

        const sql = `
            SELECT
                id,
                type,
                is_read AS isRead,
                content,
                state,
                DATE_FORMAT(create_time, '%Y-%m-%d %H:%i:%s') AS createTime
            FROM message_center
            WHERE recipient_id = ?
            ORDER BY create_time
            DESC LIMIT ?, ?
        `
        const [rows] = await mysqlPool.execute(sql, [userId, (currentPage - 1) * pageSize, pageSize])
        return { total, rows }
    }

    // 设置消息状态为已读
    static async setMsgRead(userId, msgId) {
        const sql = `update message_center set is_read = 1 where id = ? and recipient_id = ?`
        const [result] = await mysqlPool.execute(sql, [msgId, userId])
        return result
    }

    // 获取用户未读消息数量
    static async getNoReadMsgCount(userId) {
        const sql = `select count(*) as total from message_center where recipient_id = ? and is_read = 0`
        const [result] = await mysqlPool.execute(sql, [userId])
        return result[0].total
    }
}

module.exports = Message
